//
//  StoreConfigureViewController.swift
//  DSHCMerchant
//
//  Created by 罗德良 on 2018/4/12.
//  Copyright © 2018年 袋鼠好车. All rights reserved.
//

import UIKit
import Alamofire
import CRRefresh

class StoreConfigureViewController: BaseViewController {

    let storeconfigCell = "storeconfigCell"
    var storeServices : [ServiceModel]?
    
    
    @IBOutlet var storeConfigTableview: UITableView!
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        requstStoreConfigList()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configView()
    }
    
    func configView() -> Void {
        storeConfigTableview.delegate = self
        storeConfigTableview.dataSource = self
        storeConfigTableview.separatorStyle = .none
        storeConfigTableview.showsVerticalScrollIndicator = false
        storeConfigTableview.backgroundColor = BaseColor.BackGroundColor
        storeConfigTableview.register(UINib(nibName: "StoreConfigTableViewCell", bundle: nil), forCellReuseIdentifier: storeconfigCell)
        storeConfigTableview.cr.addHeadRefresh(animator: SlackLoadingAnimator() as CRRefreshProtocol) { [weak self] in
            self?.requstStoreConfigList()
        }
    }
    
    //网络请求
    //店铺配置列表
    func requstStoreConfigList() -> Void {
        
        Alamofire.request(storeConfigListUrl, method:.post, parameters: ["sid":UserModel.shareUser.data?.storeId ?? String()])
            .responseString { response in
                self.storeConfigTableview?.cr.endHeaderRefresh()
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = BaseResponseOfModel<BaseArrayData<ServiceModel>>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:

                            self.storeServices = basemodel.data?.data
                        print("数据请求成功")
                        self.storeConfigTableview.reloadData()
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                        
                    }
                    
                case false:
                    print(response.result.error!)
                }
        }
    }
    
    //停,启用服务
    func requestDoService(serviceId:String,status:String) -> Void {
        
        
        Alamofire.request(turnStoreServiceUrl, method:.post, parameters:["server_id":serviceId,"status":status,"sid":UserModel.shareUser.data?.storeId ?? String()])
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = DefaultData()
                    basemodel = DefaultData.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                        self.requstStoreConfigList()
                    case false:
                        MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}


extension StoreConfigureViewController: UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.storeServices?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
            let cell = tableView.dequeueReusableCell(withIdentifier: storeconfigCell, for: indexPath) as! StoreConfigTableViewCell
            cell.selectionStyle = .none
            let model = self.storeServices![indexPath.item]
            cell.serviceHeaderLabel.text = model.name
            var serviceChilds = [String]()
            if (model.son?.count)! > 0 {
                for service in model.son! {
                serviceChilds.append(service.name)
                }
            cell.servicesContentLabel.text = serviceChilds.joined(separator: " ")
            }else {
            cell.servicesContentLabel.text = ""
        }
    
        if model.use_status == "1" {
        cell.serviceTurnBtn.setImage(UIImage.init(named: "启用icon")?.withRenderingMode(.alwaysOriginal), for: .normal)
            
        }else {
        cell.serviceTurnBtn.setImage(UIImage.init(named: "停用icon")?.withRenderingMode(.alwaysOriginal), for: .normal)
        }
        
        cell.turnStatusBlock {
            if model.use_status == "1" {//停用服务
                let alertController = UIAlertController(title: "操作服务",
                                                        message: "您确定要停用该服务吗？", preferredStyle: .alert)
                let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
                let okAction = UIAlertAction(title: "停用", style: .default, handler: {
                    action in
                    print("停用")
                    self.requestDoService(serviceId: model.id, status: "0")
                })
                alertController.addAction(cancelAction)
                alertController.addAction(okAction)
                self.present(alertController, animated: true, completion: nil)
            }else {//启用服务
                let alertController = UIAlertController(title: "操作服务",
                                                        message: "您确定要启用该服务吗？", preferredStyle: .alert)
                let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
                let okAction = UIAlertAction(title: "启用", style: .default, handler: {
                    action in
                    print("启用")
                    self.requestDoService(serviceId: model.id, status: "1")
                })
                alertController.addAction(cancelAction)
                alertController.addAction(okAction)
                self.present(alertController, animated: true, completion: nil)
            }
        }


            return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            return ScaleHeight(80)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
         let model = self.storeServices![indexPath.item]
        let childServiceVC = StoreConfigChildServiceViewController()
        childServiceVC.title = model.name;
        childServiceVC.childServiceId = model.id
        self.navigationController?.pushViewController(childServiceVC, animated: true)
    }
    //    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    //        return 10
    //    }
    
}



